/**
 * <p>Title: DBManager.java</p>
 * <p>Description: CS 343 Final Project. This class will allow for music during the game</p>
 * @author Tim Olmstead, Brady Fetting, Erik Brown, Thales Kirk
 * @email timothy.olmstead@my.uwrf.edu, brady.fetting@my.uwrf.edu, 
 * 			erik.brown@my.uwrf.edu, thales.kirk@my.uwrf.edu
 * @date November 15, 2013
 */
package Components;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import java.util.Collections;
import java.util.List;

public class DBManager {

	/**
	 * @param newRecord
	 * @description sets the record leaderboard in the db
	 */
	public void setRecord(Record newRecord) {

		// Create an inventory of Widgets

		// RecordList.add( new Record( username, score, mph) );

		final String PERSISTENCE_UNIT_NAME = "Records";
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

		EntityManager em = factory.createEntityManager();

		// create new widget to persist into the db
		em.getTransaction().begin();

		// Persist all widgets
		em.persist(newRecord);

		em.getTransaction().commit();
		em.close();

	}

	/**
	 * @param none
	 * @description gets the record from the db
	 */
	@SuppressWarnings("unchecked")
	public List<Record> getRecords() {


		final String PERSISTENCE_UNIT_NAME = "Records";
		EntityManagerFactory factory = Persistence
				.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);

		EntityManager em = factory.createEntityManager();

		// create new widget to persist into the db
		em.getTransaction().begin();

		// Get the entire Inventory of Widgets from the database
		Query q = em.createQuery("select w from Record w");
		List<Record> RecordInventory = q.getResultList();

		// Print all widgets from the database

		if (RecordInventory.isEmpty()) {
			RecordInventory.add(new Record("Segway Jake", 100, 12));
			RecordInventory.add(new Record("Segway Steve", 200, 13));
			RecordInventory.add(new Record("Segway Brady", 300, 14));
			RecordInventory.add(new Record("Segway Douchington", 400, 15));
			RecordInventory.add(new Record("Segway Buckwild", 500, 16));
			RecordInventory.add(new Record("Segway Eric", 600, 17));
			RecordInventory.add(new Record("Segway CrazyCat", 700, 18));
			RecordInventory.add(new Record("Segway Thales", 800, 19));
			RecordInventory.add(new Record("Segway Stockingmaster", 900, 20));
			RecordInventory.add(new Record("Segway Tim", 1000, 21));

			// Print all widgets from the database
			for (Record w : RecordInventory)
				em.persist(w);

			em.getTransaction().commit();

		}

		em.close();

		Collections.sort(RecordInventory);

		return RecordInventory;

	}
}
